package com.caituo.idouyou.user.common.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.sun.org.apache.bcel.internal.generic.NEW;

public class JSONUtil {
	
	private static final Log log = LogFactory.getLog(JSONUtil.class);
	
	public static void main(String[] args) {
		//1.将List对象序列化为Json文本
		List list = new ArrayList();
		list.add(1);
		list.add(2);
		System.out.println(JSONUtil.toJSONString(list));
	}
	
	
	/**
	 * 将List对象序列化为JSON文本
	 */
	public static <T> String toJSONString(List<T> list){
		JSONArray jsonArray = new JSONArray(list);
		return jsonArray.toString();
	}
	
	 /***
     * 将对象序列化为JSON文本
     * @param object
     * @return
     */
	 public static String toJSONString(Object object){
	        JSONArray jsonArray = null;
			try {
				jsonArray = new JSONArray(object);
			} catch (JSONException e) {
				log.error(e.getMessage());
				//e.printStackTrace();
			}
	        return jsonArray.toString();
	 }
	 
	 /***
     * 将JSON对象数组序列化为JSON文本
     * @param jsonArray
     * @return
     */
	 public static String toJSONString(JSONArray jsonArray){
	        return jsonArray.toString();
	 }
	 
	 
	 /***
     * 将JSON对象序列化为JSON文本
     * @param jsonObject
     * @return
     */
    public static String toJSONString(JSONObject jsonObject)
    {
        return jsonObject.toString();
    }   
	
    /***
     * 将对象转换为List对象
     * @param object
     * @return
     */
    public static List toArrayList(Object object)
    {
        List arrayList = new ArrayList();

        JSONArray jsonArray = new JSONArray(object);

        Iterator it = jsonArray.iterator();
        while (it.hasNext())
        {
            JSONObject jsonObject = (JSONObject) it.next();

            Iterator keys = jsonObject.keys();
            while (keys.hasNext())
            {
                Object key = keys.next();
                Object value = jsonObject.get(key);
                arrayList.add(value);
            }
        }

        return arrayList;
    }

}
